package com.member.common.utils.fy;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class HttpUtil {

	public static String postForm(String url, Map<String, String> paramMap) {
		try {
            log.info("HttpUtil.postForm调用开始,url=={},参数=={}", url, paramMap);
			Request request = Request.Post(url);
			request.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			Form form = Form.form();
			for (String key : paramMap.keySet()) {
				form.add(key, paramMap.get(key));
			}
			Response response = request.bodyForm(form.build(), StandardCharsets.UTF_8).execute();
			if (response != null) {
				Content content = response.returnContent();
                log.info("HttpUtil.postForm调用返回结果=={}", content.asString());
				return content.asString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String postJson(String url, String json) {
		try {
            log.info("HttpUtil.postJson调用开始,url=={},参数=={}", url, json);
			Request request = Request.Post(url);
			request.addHeader("Content-Type","application/json");
			Response response = request.bodyString(json,ContentType.APPLICATION_JSON).execute();
			if (response != null) {
				Content content = response.returnContent();
                log.info("HttpUtil.postJson调用返回结果=={}", content.asString());
				return content.asString();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}
}
